#include "dialog.h"
#include "ui_server.h"

#include <QTableView>
#include <QSqlTableModel>
#include <QtGui>
#include <QtSql>
#include <QtDebug>
#include <QEvent>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);


    db = QSqlDatabase::addDatabase( "QSQLITE" );

    db.setDatabaseName("../xyz.db");

    if ( !db.open() )
    {
        qDebug() << db.lastError();
        qDebug() << "Error: Unable to connect due to above error";
        exit(1);
    } //end of error check


//    if(closeEvent())
//    {
//        connect(ui->quitButton, SIGNAL(clicked()), this, SLOT(quitfunction()));
//    }

//    bool accpt = isAccepted();
//    bool close = true;

//    if(close == accpt)
//    {
//        quitfunction();
//    }

    connect(ui->candidatesButton, SIGNAL(clicked()), this, SLOT(candidatefunction()));
    connect(ui->ballotsButton, SIGNAL(clicked()), this, SLOT(ballotfunction()));
    connect(ui->votersButton, SIGNAL(clicked()), this, SLOT(voterfunction()));
    connect(ui->quitButton, SIGNAL(clicked()), this, SLOT(quitfunction()));

} // end main dialog


void Dialog::candidatefunction()
{

    model = new QSqlTableModel(); //creates a new model for the table
    model->setTable("candidates");

    model->select();

    view1 = new QTableView();
    view1->setModel(model);

    view1->setEditTriggers(false);
    view1->show();
//    QSqlQueryModel* model = new QSqlQueryModel();
//    model->setQuery("SELECT * FROM Candidates");
//    view = new QTableView();
//    view->setModel(model);
//    view->show();

}

void Dialog::ballotfunction()
{
    model = new QSqlTableModel(); //creates a new model for the table
    model->setTable("ballots");

    model->select();

    view2 = new QTableView();
    view2->setModel(model);

    view2->setEditTriggers(false);
    view2->show();

}

void Dialog::voterfunction()
{
    model = new QSqlTableModel(); //creates a new model for the table
    model->setTable("voters");

    model->select();

    view3 = new QTableView();
    view3->setModel(model);

    view3->setEditTriggers(false);
    view3->show();

}

void Dialog::quitfunction()
{
    QSqlQuery voteclear("SELECT * FROM candidates");

    while(voteclear.next())
    {
        QSqlQuery cand;
        cand.exec("UPDATE candidates SET totalvotes = 0");

    }

    QSqlQuery ballotclear("SELECT * FROM ballots");

    while(ballotclear.next())
    {
        QSqlQuery clear;
        clear.exec("DELETE FROM ballots");
    }


        view1->close();
        view2->close();
        view3->close();


}


Dialog::~Dialog()
{
    delete view1;
    delete view2;
    delete view3;
    delete model;

    db.close();
    db.removeDatabase("QSQLITE");

    delete this;
    delete ui;
}
